function getCookie(name){
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    try {
        return (arr = document.cookie.match(reg)) ? decodeURIComponent(arr[2]) : null;
    } 
    catch (e) {
        return null;
    }
}  
function setCookie(name, value, expire, domain){
    function _setCookie(name, value, expire, domain){
        var exp = new Date();
        exp.setTime(exp.getTime() + expire);
        var str = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + ";path=/;";
        if (domain && domain != 'localhost') {
            str += "domain=" + domain;
        }
        document.cookie = str;
    }
	var exp = (typeof expire == "number") ? expire : 365 * 24 * 60 * 60 * 1000;
    _setCookie(name, value, exp, domain);
}
	
var _m = chrome.i18n.getMessage, userInfo, guard={
	docReady:false,
	userRun:false,
	userViewMode:null,
	refreshImgCountHandle:null,
	refreshImgCount:0,
	refreshImgMaxCount:15,
	refreshImgCountInterval:400,
	onScrollHandler:null,
	onScrollInterval:500,
	lastScrollTop:0,
	petEntity:null,
	ready:function(){
		this.docReady = true;
		if (this.userRun){
			this.run();
		}
	},
	run:function(viewMode){
		viewMode = viewMode || this.userViewMode;
		happyReader.main(viewMode);
		this.clearRefreshImgHandle();
		document.onkeydown=document.onkeypressed=document.onkeyup=null;
		document.body.onkeydown=document.body.onkeypressed=document.body.onkeyup=null;
	},
	showTip:function(){
		var tip = $.createEle('div', {className:''}, {cssText:'z-index:999999;position:absolute;top:40%;left:40%;padding:5px 40px;line-height:60px;font-size:25px;color:#fff;text-align:center;opacity:1;background:rgba(0,0,0,.65);border-radius:6px;-webkit-transition: all .6s linear;'})
		  .html(_m('guardTip'))
		  .appendTo($('body'));
		  
		setTimeout(function(){
		   tip.css({opacity:0});
		   setTimeout(function(){$.removeEle(tip);}, 600);
		}, 600);
	},
	clearRefreshImgHandle:function(){
		clearTimeout(this.refreshImgCountHandle);
        this.refreshImgCountHandle = null;
	},
	refreshImg:function(){
		guard.refreshImgCountHandle = setTimeout(function(){
			if (guard.refreshImgCount++ <= guard.refreshImgMaxCount) {
				guard.refreshImgCountInterval = 1.5*guard.refreshImgCountInterval|0;
				guard.updatePet();
				guard.refreshImg();
			}else{
				guard.clearRefreshImgHandle();
			}
		}, guard.refreshImgCountInterval);
	},
	clickPetTabAnimate:function(self, type){
		type = self.id.replace('happyReader', '').replace('Tab', '').toLowerCase();
		$(self).css({opacity:0,webkitTransform:'scale(2.5)'});
		setTimeout(function(){guard.run(type)},500);
	},
	updatePet:function(){
		if (!options_enableAnalysisHelper)return;
        happyReader.getImgData();
        if (happyReaderImg.checkModeValid()){
            guard.petEntity ? $('#happyReaderImgTab').attr({className:'enable', onclick:function(){guard.clickPetTabAnimate(this)}}) : guard.createPet();
            happyReaderImg.imgData.big.length && $('#happyReaderImgCount').html(happyReaderImg.imgData.big.length);
        }
    },
	createPet:function(){
		if (this.petEntity)return ;
		
		$.loadfile({
		  'type':'css', 
		  'url':chrome.extension.getURL('css/happyReaderPet.css')
		});
		
		var html = '<img src="'+chrome.extension.getURL('img/icon-48.png')+'"/><b id="happyReaderImgCount"></b>';
		html += options_enableTabs.Img ? '<a id="happyReaderImgTab">'+_m("img")+'</a>' : '';
		html += options_enableTabs.Text ? '<a id="happyReaderTextTab">'+_m("text")+'</a>' : '';
		html += options_enableTabs.Link ? '<a id="happyReaderLinkTab">'+_m("link")+'</a>' : '';
		this.petEntity = $.createEle(
		  'div', 
		  {id:'happyReaderPet'}
		)
		.html(html)
		.appendTo($('body'));
		
		for(var item in options_enableTabs) {
			options_enableTabs[item] && window['happyReader'+item].checkModeValid() && $('#happyReader'+item+'Tab').attr({className:'enable', onclick:function(){guard.clickPetTabAnimate(this)}});
		}
	}
}

var options_hotkey, 
    isTabForNextPage = false, 
	setting_textSkin = null,
	options_enableTabs = null,
	options_enableAnalysisHelper = false, 
	options_enableSuperAutoNextPage = false, 
	options_enableShare = false,
	guardConn = chrome.extension.connect({name:'guardConn'}),
	nextPageConn = chrome.extension.connect({name:'nextPageConn'});

guardConn.postMessage({action:'get'});
guardConn.onMessage.addListener(function(msg){
	//set userInfo
	userInfo = msg.userInfo;
    if (userInfo && location.hostname == 'os.heimali.com') {
        setCookie("token", userInfo.token);
        setCookie("uid", userInfo.uid);
        setCookie("name", userInfo.name);
    }
	
	//set isTabForNextPage
	if (msg.isTabForNextPage){
        isTabForNextPage = true;
		var nextPageHandler = setInterval(function(){
			if (['complete', 'interactive'].indexOf(document.readyState) > -1) {
                $('body').css({'overflow':'hidden'});
                $.createEle('div', {id:'happyReader_getNextPageMask'}, {position:'absolute', width:'100%', height:document.body.scrollHeight+'px', zIndex:9999999, background:'#000', opacity:.8}).html('<p style="margin:300px 0 0;font-size:40px;color: white;text-align:center;">Don\'t Closed</p>').appendTo($('body'));
				clearInterval(nextPageHandler);
				nextPageHandler = null;
			}
		}, 300);
    }
	
	//set options setting
	setting_textSkin = msg.setting_textSkin;
    options_hotkey = msg.options_hotkey;
	options_enableTabs = msg.options_enableTabs;
    options_enableAnalysisHelper = msg.options_enableAnalysisHelper;
    options_enableSuperAutoNextPage = msg.options_enableSuperAutoNextPage;
	options_enableShareBtn = msg.options_enableShareBtn;
    if (options_enableAnalysisHelper === ''){
       options_enableAnalysisHelper = 1;
       guardConn.postMessage({action:'setOptionsEnableAnalysisHelper', value:options_enableAnalysisHelper});
    }
    if (options_enableSuperAutoNextPage === ''){
       options_enableSuperAutoNextPage = 1;
       guardConn.postMessage({action:'setOptionsEnableSuperAutoNextPage', value:options_enableSuperAutoNextPage});
    }
	if (options_enableShareBtn === ''){
       options_enableShareBtn = 1;
       guardConn.postMessage({action:'setOptionsEnableShareBtn', value:options_enableShareBtn});
    }
});

nextPageConn.postMessage({action:'getTopicAuthor',topic:(location.host+location.pathname)});
nextPageConn.onMessage.addListener(function(msg){
	if (msg.action == 'getTopicAuthorResponse'){
		happyReaderText.topicAuthor = msg.value.author;
	}
});

document.addEventListener('keydown', function(e){
	var keyCode = e.keyCode;
	
	//esc
    if (keyCode == 27) {
        setTimeout(function(){location.reload()},100)
        return ;
    }
	
	//maskImg 
	if (happyReaderImg.maskShown) {
		if ([37, 38, 72, 75, 65, 87].indexOf(keyCode) > -1){
			happyReaderImg.preMaskImg();
		}else if ([39, 40, 74, 76, 68, 83].indexOf(keyCode) > -1) {
			happyReaderImg.nextMaskImg();
		}
		return;
	}
	
	if (options_hotkey && options_hotkey.enable){
		var map = {ctrl:'ctrlKey', alt:'altKey', shift:'shiftKey'}, funcKeys=[];
		for(var item in options_enableTabs) {
			var res = false, item = item.toLowerCase();
			item = (item=='img') ? 'image' : item;
			options_hotkey[item].split('+').forEach(function(hotkey){
                var key = hotkey.toLowerCase();
                if (map[key]){
                    funcKeys.push(map[key]);
                }else if(keyCode == key.charCodeAt() || keyCode == key.toUpperCase().charCodeAt()){
                    res = true;
                    funcKeys.forEach(function(funcKey){
                        res = res && e[funcKey];
                    });
                }
                
                if (res){
                    guard.userRun = true;
                    guard.userViewMode = (item=='image' ? 'img' : item);
                    guard.docReady ? guard.run() : guard.showTip();
                }
            });
		}
	}
}, false);

var guardHandle  = setInterval(function(){
	if (['complete', 'interactive'].indexOf(document.readyState)>-1){
	   guard.ready();
	   clearInterval(guardHandle);
       guardHandle = null;
	   
	   if (isTabForNextPage){
            happyReader.getNextPageUrl();
			var curContent = happyReaderText.getData(),
			    curImgs = happyReaderImg.getData(document);
			nextPageConn.postMessage({action:'setNextPage', url:happyReader.nextPageUrl, content:curContent, img:JSON.stringify(curImgs)});
			happyReader.nextPageUrl ? location.href = happyReader.nextPageUrl : nextPageConn.postMessage({action:'noNextPage'});
			return ;
	   }
	   
	   try{
		   if (!options_enableAnalysisHelper) {
                return;
		   }
		   
		   happyReader.getData();
		   
		   if (!happyReaderImg.checkModeValid() && !happyReaderText.checkModeValid()) {
                return;
		   }
		   guard.createPet();
		   guard.refreshImg();
	   }catch(e){}
	}
}, 200);

window.addEventListener('load', function(){
	guard.clearRefreshImgHandle();
});

window.addEventListener('scroll', function(){
	if (happyReader.isRun)return;
	var scrollTop = document.body.scrollTop;
	if (guard.onScrollHandler || scrollTop <= guard.lastScrollTop)return;
	guard.lastScrollTop = scrollTop;
	guard.onScrollHandler = setTimeout(function(){
		guard.updatePet();
		guard.onScrollHandler = null;
	}, guard.onScrollInterval);
});

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
	if (request.callExtMode == 'rightMenu') {
		happyReaderText.rightMenuContent = document.getSelection().toString();
		guard.userRun = true;
		guard.run('text');
		return ;
	}
	
	if (guard.userRun && guard.docReady){
		return;
	}
	
	guard.userRun = true;
	if (request.callExtMode == 'rigthMenu') {
		guard.run('text');
	}else {
		guard.docReady ? guard.run() : guard.showTip();
	}
    sendResponse({});
});

function setTextSkin(skin){
	for(var k in skin){
        if (setting_textSkin[k] != skin[k]){
            if (k == 'bg'){
                happyReaderText.updateTextSkinBg(skin.bg);
            }else if (k == 'fontSize') {
                happyReaderText.updateFontSize(skin.fontSize);
            }else if (k == 'pageWidth') {
                happyReaderText.resetTextPageWidthValue(skin.pageWidth);
            }
        }
    }
    setting_textSkin = skin;
}

//use super next page && update config
chrome.extension.onConnect.addListener(function(port){
	port.onMessage.addListener(function(msg){
		
		function updateTextMode(content){
			if (!content)return;
			
			happyReader.curPage++;
            $.removeEle($('#textCanvas_loading'));
            $.createEle('article').css({background: happyReaderText.getTextSkinBg(),width:happyReaderText.getArticlePageWidth(happyReaderText.getTextPageWidth())}).html("<span class='hrRemove'><b>X</b></span><page>" + happyReader.curPage + "/<totalPage>1</totalPage></page><div class='happyReaderEditable' style='padding:0 8px;'>" + (msg.content || "<p>" + _m("noText") + "</p></div>")).appendTo($('#textCanvas'));
            $.createEle('div', {id: 'textCanvas_loading'}).html('Loading .... ').appendTo($('#textCanvas'));
            happyReaderText.updateFontSize(happyReaderText.getFontSize());
            
            var totalPages = document.getElementsByTagName('totalPage');
            for (var i = 0, totalPage; totalPage = totalPages[i++];) {
                totalPage.innerHTML = happyReader.curPage;
            };
            //clear first page min-height
            document.querySelector('#textCanvas article').style.minHeight=0;
		}
		
		function updateImgMode(content){
			if (!content)return;
			
			var data = JSON.parse(msg.img),
                    imgData = happyReaderImg.imgData;
                
                var srcArr = [];
                imgData.big.forEach(function(item){
                    srcArr.push(item.src);
                });
                data.big.forEach(function(item){
                    if (srcArr.indexOf(item.src) >= 0)return;
                    srcArr.push(item.src);
                    happyReaderImg.imgData.big.push(item);
                });
                
                //happyReaderImg.imgData.big = $.mergeArray(imgData.big, data.big);
                //happyReaderImg.imgData.normal = $.mergeArray(imgData.normal, data.normal);
                //happyReaderImg.imgData.small = $.mergeArray(imgData.small, data.small);
                $('#bigPicCount').html(happyReaderImg.imgData.big.length);
                //$('#normalPicCount').html(happyReaderImg.imgData.normal.length);
                //$('#smallPicCount').html(happyReaderImg.imgData.small.length);
                happyReaderImg.render();
		}
		
		if (options_enableSuperAutoNextPage) {
			if (msg.action == 'setNextPage') {
				//update text mode
				updateTextMode(msg.content);
				//update img mode
				updateImgMode(msg.img);
				
			}else if (msg.action == 'noNextPage' || msg.action == 'cancelNextPage') {
				happyReaderText.bindRemoveArticleBtn();
				$.removeEle($('#textCanvas_loading'));
			}
		}
		
		if (msg.action == 'updateTextSkin'){
			setTextSkin(msg.textSkin);
		}
		
		function updateShareBtn() {
            var shares = document.querySelectorAll('article p.share');
            for(var idx in shares) {
                if (shares[idx].style) {
					shares[idx].style.display = options_enableShareBtn ? 'block' : 'none';
				}
            }
        }
		
		if (msg.action == 'updateShareBtn') {
            options_enableShareBtn = msg.value;
            updateShareBtn();
        }
        
		if (msg.action == 'syncConfig') {
			var newConfig = JSON.parse(msg.value);
			if (!newConfig)return ;
		    setTextSkin(newConfig.setting_textSkin);
			options_hotkey = newConfig.options_hotkey;
		    options_enableAnalysisHelper = newConfig.options_enableAnalysisHelper;
		    options_enableSuperAutoNextPage = newConfig.options_enableSuperAutoNextPage;
			options_enableShareBtn = newConfig.options_enableShareBtn;
			updateShareBtn();
		}
		
		if (msg.action == 'syncLoginInfo') {
			userInfo = msg.value.userInfo;
			if ($('#textDownload').length){
				happyReaderText.bindDownloadTxt();
			}
			if ($('#textCollect').length) {
				happyReaderText.bindTextCollect();
			}
		}
	});
});
